<?php
/**********************************************************************
 *                                                                    *    
 * Copyright (c) 2009 Dmytro Bezhnar. All rights reserved.                    *
 *                                                                    *
 **********************************************************************/

/**
 * Phones2 Manager. New level phone manager for RIA clients DB
 *
 * @version $Id: Phones2Manager.php,v 1.29 2008/06/04 15:38:25 master Exp $
 */

class Phones2Manager extends ORMManager
{
   /**
    * ����� ������������
    * @var integer
    */
    public $user_id = null;

   /**
    * ����� ����������
    * @var integer
    */
    public $city_id = null;

    public $phones2_db = null;
    
    public $insert_prog_id = 2;
    
    /**
     * Enter description here...
     *
     * @var Phones2 Object
     */
    public $phones;
    

	function __construct($user_id=0,$city_id=0) {
		parent::__construct();
		$this->user_id = $user_id;
		$this->city_id = $city_id;
		$phones2_db = new Phones2DB();
		$this->phones2table = $phones2_db->__table;
		setlocale(LC_ALL, 'ru_RU.cp1251');
	}
	
	function parsePhones($phonesStr) {
		$this->phones = new Phones2($phonesStr);
		return $this->phones->is_found_error();
	}
	
	/**
	 * Add phones to DB
	 *
	 */
	function addToDB() {
		if ($this->user_id) {
			foreach ($this->phones->get_phones() as $phone) {
				$this->addPhoneItemToDB(& $phone);
			}
			return true;
		} else {
			return false;
		}
	}
	
	function addNewToDB($phone_str, $user_id, $city_id, $is_hidden = 0, $is_checked = 0){
		$new_count = 0;
		
		$this->parsePhones($phone_str);
		$phones_new = $this->phones->get_phones();
		
		$this->user_id = $user_id;
		$this->city_id = $city_id;
		$phones_db = $this->searchPhones();
		
		foreach ($phones_new as &$phone){
			if (!$phone['Valid']) break;
			
			$is_found = 0;
			foreach ($phones_db as $phone_db) {
				if (preg_match('%'.$phone['Val'].'%', $phone_db['phone']) || preg_match('%'.$phone_db['phone'].'%', $phone['Val'])) {
					$is_found = 1;
					break;
				}
			}
			
			if (!$is_found) {
				$new_count++;
				$phone['is_hidden'] = $is_hidden;
				$phone['is_checked'] = $is_checked;
				$this->addPhoneItemToDB($phone);
			}
		}
		
		return $new_count;
	}
	
	function updateDB() {
		global $connection;
		if ($this->user_id) {
			$processed_arr = array();
			$phones_manager_old = new Phones2Manager($this->user_id,$this->city_id);
			$phones_manager_old->getFromDB();
			foreach ($phones_manager_old->phones->phones_idx as $phoneVal => $phone) {
				if (isset($this->phones->phones_idx[$phoneVal])) {
					$qs = "update ".$this->phones2table." set phone_str = '".$this->checkTextForMysql($phone['Str'],false)."' where user_id = ".$this->user_id." and phone = ".$phone['Val'];
					$this->execQuery($qs);
				} else {
					$this->delPhoneFromDB($phone);
				}
				$processed_arr[$phoneVal] = 1;
			}
			foreach ($this->phones->phones_idx as $phoneVal => &$phone) {
				if (!isset($processed_arr[$phoneVal])) {
					$this->addPhoneItemToDB($phone);
				}
			}
			return true;
		} else {
			return false;
		}
		
	}
	
	function addPhoneItemToDB($phone,$is_hidden) {
		if ($phone['Valid']) {
			$phones2_db = new Phones2DB();
			$phones2_db->user_id = $this->user_id;
			$phones2_db->city_id = $this->city_id;
			$phones2_db->phone = $phone['Val'];
			$phones2_db->phone_str = $phone['Str'];
			$phones2_db->check_not_array = array('insert_date');
			$phones2_db->insert_date = 'now()';
			$phones2_db->insert_prog_id = $this->insert_prog_id;
			$phones2_db->is_hidden = $phone['is_hidden'];
			$phones2_db->is_checked = $phone['is_checked'];
			$this->insert($phones2_db);
		}
	}
	
	/**
	 * ������ �������� ��� ����������� ������������ �� ��
	 */
	function getFromDB() {
		$this->phones = new Phones2();
		$qs = "select * from ".$this->phones2table." where user_id = ".$this->user_id;
		#print $qs;
		$list = $this->getArray($qs);
		foreach ($list as $phone_line) {
			$this->phones->push_to_phones(
				$phone_line['phone'],
				$phone_line['phone_str'],
				$phone_line['phone_id'],
				$phone_line['is_hidden'],
				$phone_line['is_checked']
			);
		}
	    if (count($list)) {
	    	$this->obl_id  = $list[0]['city_id'];
	    }		
	}

	/*
	 * �������� ������ � �������� � ���� �� phone_id 
	 * 
	 */
	function getPhoneByPhoneID($phone_id) {
		$qs = 'select * from '.$this->phones2table.' where phone_id = '.$phone_id;
		return $this->getOneArray($qs);
	}
	
	/*
	 * �������� ������ ������������� ����� �� ��������
	 */
	function getUserIDsByPhone($phone) {
		$phone = $this->normalizePhone($phone);
		$qs = 'select user_id from '.$this->phones2table.' where phone like "%'.$phone.'" group by user_id' ;
		$arr = $this->getArray($qs);
		$ret_arr = array();
		foreach ($arr as $item) {
			array_push($ret_arr,$item['user_id']);
		}
		return $ret_arr;
	}
	
	function getUserIDsByPhoneSQL($phone,$tableName,$fieldName='user_id') {
		$ret_arr = array();
		$arr = $this->getUserIDsByPhone($phone);
		foreach ($arr as $user_id) {
			array_push($ret_arr,"$tableName.$fieldName = $user_id");
		}
		return $ret_arr;
	}

	function normalizePhone($phone) {
		return preg_replace('/^(\+380|380|80|0)/','',$phone);
	}

	/*
	 * ��������� ������ � �������� � ���� �� phone_id
	 */
	function updateByPhoneID(&$dialog) {
		$phones2_db = new Phones2DB();
		$phones2_db->phone_id = $dialog->phone_id;
		$this->find($phones2_db);
		$phones2_db->city_id = $dialog->city_id;
		$phones2_db->phone = $dialog->phone;
		$phones2_db->phone_str = $dialog->phone_str;
		$phones2_db->check_not_array = array('insert_date');
		$phones2_db->insert_date = 'now()';
		$phones2_db->insert_prog_id = 2;
		$phones2_db->is_hidden = $dialog->is_hidden;
		$phones2_db->is_checked = $dialog->is_checked;
		$this->update($phones2_db);
	}

	function deleteByPhoneID($phone_id) {
		$phones2_db = new Phones2DB();
		$phones2_db->phone_id = $phone_id;
		$this->remove($phones2_db);
	}
	
	function insertPhone(&$dialog) {
		$phones2_db = new Phones2DB();
		$phones2_db->user_id = $dialog->user_id;
		$phones2_db->city_id = $dialog->city_id;
		$phones2_db->phone = $dialog->phone;
		$phones2_db->phone_str = $dialog->phone_str;
		$phones2_db->check_not_array = array('insert_date');
		$phones2_db->insert_date = 'now()';
		$phones2_db->insert_prog_id = 2;
		$phones2_db->is_hidden = $dialog->is_hidden;
		$phones2_db->is_checked = $dialog->is_checked;
		$this->insert($phones2_db);
		return $phones2_db->phone_id;
	}
	
	/**
	* ������� �������� ��� ����������� ������������ �� ��
	*/
	function delAllPhonesFromDB () {
		return $this->execQuery("delete from ".$this->phones2table." where user_id = $this->user_id");
	}

	/**
	* ������� �������� ��� ����������� ������������ �� ��
	*/
	function delPhoneFromDB ($phone,$del_hidden = false) {
		#print_r ($phone);
		if (!$phone['isHidden'] or $del_hidden) {
			$qs = "delete from ".$this->phones2table." where user_id = $this->user_id and phone = ".$phone['Val'];
			return $this->execQuery($qs);
		}
	}
	
	function isPhoneFound() {
		$found = $this->searchPhones();
		return count($found);
	}

	function isUserFound() {
		$found = $this->searchPhones();
		if (count($found)) {
			return $found[0]['user_id'];
		} else {
			return false;
		}
	}
	
	function searchPhones() {
		$qs = "select * from ".$this->phones2table." where ".$this->whereSQLMaker()." order by is_checked desc, insert_date";
		return $this->getArray($qs);
	}
	
	/**
	* ��������� ������� where ��� ���������� �������
	*
	* @param string $phoneTableName ��� ��� ����� ������� phones
	* @return string
	*/
	function whereSQLMaker($phoneTableName='') { 
		if ($phoneTableName != '') {
			$phoneTableName= $phoneTableName.'.';
		}
		$whereArr = array();
		
		foreach ($this->phones->get_phones() as $phone) {
			$whereItem = array();
			
			array_push($whereItem, $phoneTableName."phone = ".$phone['Val']);
			if ($this->city_id) array_push($whereItem, "(".$phoneTableName."city_id = ".$this->city_id." or ".$phoneTableName."city_id = 0)");
			if ($this->user_id) array_push($whereItem, $phoneTableName."user_id = ".$this->user_id);
			$str_item = '('.join(' and ',$whereItem).')';
			
			array_push($whereArr,$str_item);
		}
		if (count($whereArr)) return '('.join(' or ',$whereArr).')';
		else return 'false';
	}
	
	/**
	* ���� �� �������� � �������
	* @return boolean
	*/
	function isFound() {
		return count($this->phones->get_phones());
	}
	
 
	/**
	 * �������� �������� �� ������� ���� ����������� ������
	 */
	function getPhonesListFromImportAgencies($obl_id=0,$not_need_import=false) {
		global $options;
		$where = 'a.is_need_import';
		if ($not_need_import) {
			$where = '!'.$where;
		}
		if ($obl_id) {
			$where = $where.' and c.stateID = '.$obl_id;
		}
		$qs = "
			select ph2.phone, au.user_id
			from agencies a, agency_users au, ".$options['passport']['database'].".clients c left join ".$options['passport']['database'].".phones2 ph2 on c.clientID = ph2.user_id
			where a.agency_id = au.agency_id and au.user_id = c.clientID and ".$where;
		#print "<!-- $qs -->";
		return $this->getAssArray($qs,'phone','user_id');
	}
  
 /**
  * ��������� ������ � ������������ �� ����� ��������� � ��������� �������
  * ���������: parsePhones('53-16-13, 42-31-42') ������ ����� 531613,433124 
  * @param string $phones ������ � ����������
  function parsePhonesFromBulletin($phones) {
	$phonesArr = Array();
	$result = preg_match_all('(8\(\d{3,4}\)\d{1,3}-\d{2}-\d{2})', $phones, $found);
	while (list(,$phone) = each($found[0])) {
		$phone = preg_replace("/-/","",$phone);
		$phone = preg_replace("/\)/","",$phone);
		$phonesArr[] = preg_replace("/\(/","",$phone);
	}
	$phones=preg_replace('(8\(\d{3,4}\)\d{1,3}-\d{2}-\d{2})','',$phones);
	$result = preg_match_all('(\d{1,3}-\d{2}-\d{2})', $phones, $found);
	while (list(,$phone) = each($found[0])) {
		$phonesArr[] = preg_replace("/-/","",$phone);
	}
	$this->list = $phonesArr;
	//return($phonesArr);
  }
  */
  
/*  
	function setError($error_str)  {
		func_log($error_str, get_class($this), LOG_ERR);
	}
*/
}

?>